package com.example.aijiancece.database;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.aijiancece.database.dao.HistoryDao;
import com.example.aijiancece.database.dao.UserDao;
import com.example.aijiancece.database.entity.HistoryEntity;
import com.example.aijiancece.database.entity.UserEntity;

@Database(entities = {UserEntity.class, HistoryEntity.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase instance;

    public abstract UserDao userDao();
    public abstract HistoryDao historyDao();

    public static synchronized AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(
                    context.getApplicationContext(),
                    AppDatabase.class,
                    "app_database"
            )
            .addMigrations(MIGRATION_1_2)
            .build();
        }
        return instance;
    }

    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            // 创建新表
            database.execSQL(
                "CREATE TABLE history_new (" +
                "id TEXT PRIMARY KEY NOT NULL," +
                "content TEXT," +
                "result TEXT," +
                "analysis TEXT," +
                "timestamp INTEGER NOT NULL)"
            );

            // 复制数据
            database.execSQL(
                "INSERT INTO history_new (id, content, result, timestamp) " +
                "SELECT id, content, result, strftime('%s', time) * 1000 " +
                "FROM history"
            );

            // 删除旧表
            database.execSQL("DROP TABLE history");

            // 重命名新表
            database.execSQL("ALTER TABLE history_new RENAME TO history");
        }
    };
} 